library(magrittr)
library(stringr)
library(plyr)
library(tidyverse)
library(readxl)
library(stargazer)


rm(list=ls())
home = 'C:/Users/jdt34/Dropbox/VNA_Responsiveness/Short Article/JOP-dataverse/'


survey = paste0(home, 'Data/survey-outcomes.xlsx') %>%
  read_xlsx %>%
  transform(Treatment=factor(Treatment, levels=c('Control','Citizen','Firm')),
            Missing=as.integer(is.na(Q1))) %>%
  merge(delegates, by='ID', all.x=T)


pooled_texts = paste0(home, 'Data/pooled-outcomes.xlsx') %>%
  read_xlsx %>%
  transform(Treatment=factor(Treatment, levels=c('Control','Citizen','Firm')))


tableA05.1 = subset(survey, !is.na(Treatment)) %>%
  dlply('Treatment', function(x) {
    data.frame(Mean=round(c(mean(x$FullTime), mean(x$CentNom), mean(x$Competitive), mean(x$Prop.Citizen), mean(x$Prop.Firm)), 3),
               SD=round(c(sd(x$FullTime), sd(x$CentNom), sd(x$Competitive), sd(x$Prop.Citizen), sd(x$Prop.Firm)), 3),
               Missing=c('','','','',''),
               stringsAsFactors=F)
  }) %>%
  do.call(cbind, .) %>%
  set_rownames(c('Full-time','Central Nominee','Competitively elected','% citizen','% firm')) %>%
  set_colnames(c('Mean-con','SD-con','NA-con','Mean-cit','SD-cit','NA-cit','Mean-firm','SD-firm','NA-firm'))


tableA05.1 = subset(survey, !is.na(Treatment)) %>%
  dlply('Treatment', function(x) {
    data.frame(Mean=mean(x$Q1, na.rm=T),
               SD=sd(x$Q1, na.rm=T),
               Missing=sum(is.na(x$Q1)),
               stringsAsFactors=F)
  }) %>%
  do.call(cbind, .) %>%
  set_rownames('Prepared for debate') %>%
  set_colnames(c('Mean-con','SD-con','NA-con','Mean-cit','SD-cit','NA-cit','Mean-firm','SD-firm','NA-firm')) %>%
  rbind(tableA05.1, .)


tableA05.1 = subset(pooled_texts, !is.na(Treatment)) %>%
  dlply('Treatment', function(x) {
    data.frame(Mean=mean(x$Spoke),
               SD=sd(x$Spoke),
               Missing='',
               stringsAsFactors=F)
  }) %>%
  do.call(cbind, .) %>%
  set_rownames('Spoke') %>%
  set_colnames(c('Mean-con','SD-con','NA-con','Mean-cit','SD-cit','NA-cit','Mean-firm','SD-firm','NA-firm')) %>%
  rbind(tableA05.1, .)


stargazer(tableA05.1, 
          summary=F, 
          header=F,
          title='Basic summary statistics.', 
          align=T, 
          no.space=T, 
          label='tab:balance') %>%
  writeClipboard
